<template>
    <div class="table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>科目：</label>
                <div class="table-query-input">
                    <el-cascader
                        v-model="queryData.categoryIds"
                        :options="categoryList"
                        :props="categoryProps"
                        clearable
                    ></el-cascader>
                </div>
            </div>
            <div class="search-item">
                <label>名称：</label>
                <div class="table-query-input">
                    <el-input
                        v-model="queryData.name"
                        clearable
                        placeholder="名称"
                    ></el-input>
                </div>
            </div>
            <div class="search-item">
                <label>sku属性：</label>
                <el-cascader v-model="queryData.skuAttrIds" clearable :options="skuAttrList" :show-all-levels="false"
                             :props="props"></el-cascader>
            </div>
            <div class="search-item">
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    :loading="tableLoading"
                    @click="clickSearch()"
                >搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button
                    icon="el-icon-refresh"
                    :loading="tableLoading"
                    @click="resetSearch()"
                >重置
                </el-button>
            </div>
        </div>
        <div class="table-data-box">
            <el-table
                ref="table"
                v-loading="tableLoading"
                :data="tableData"
                border
                style="width: 100%;min-height:40em"
                row-key="id"
                @selection-change="tableSelectionChange"
            >
                <el-table-column type="selection" width="55" align="center">
                </el-table-column>
                <el-table-column
                    prop="name"
                    label="名称"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    prop="industryName"
                    label="行业名称"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    prop="examName"
                    label="考试名称"
                    min-width="100"
                ></el-table-column>
                <el-table-column
                    prop="agentPrice"
                    label="代理价格￥"
                    min-width="100"
                >
                    <template slot-scope="scope">
                        {{ priceChange(scope.row.agentPrice) }}
                    </template>
                </el-table-column>

                <el-table-column
                    prop="categoryNameList"
                    label="所属科目"
                    min-width="100"
                >
                    <template slot-scope="scope">
                        <el-tag v-for="(item) in scope.row.categoryNameList" :key="item">{{ item }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="skuAttrNameList"
                    label="sku属性"
                    min-width="100"
                >
                    <template slot-scope="scope">
                        <el-tag v-for="(item) in scope.row.skuAttrNameList" :key="item">{{ item }}</el-tag>
                    </template>
                </el-table-column>
                <el-table-column
                    label="操作"
                    width="200"
                    align="center"
                    fixed="right"
                >
                    <template slot-scope="scope">
                        <el-button
                            v-if="!scope.row.edit"
                            class="primary"
                            type="text"
                            size="mini"
                            icon="el-icon-edit"
                            :loading="scope.row.opLoading"
                            @click="openCourse(scope.row)"
                        >开课
                        </el-button>
<!--                        查看sku所包含的所有栏目-->
                        <el-button type="text" class="primary" @click="showColumns(scope.row)">
                            栏目
                        </el-button>
                        <el-button
                            v-if="scope.row.enable"
                            :loading="scope.row.opLoading"
                            type="text"
                            size="mini"
                            class="warning"
                            icon="el-icon-lock"
                            @click="openCode(scope.row)"
                        >提码
                        </el-button>

                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div v-if="pageData.total" class="xy-between table-page-box">
            <el-pagination
                background
                :current-page.sync="pageData.currentPage"
                :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize"
                layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total"
            >
            </el-pagination>
        </div>
        <el-dialog
            :title="dialogFormTitle"
            :modal="false"
            :visible.sync="dialogFormVisible"
            :before-close="dialogClose"
            custom-class="two-dialog"
        >
            <el-form
                ref="dataForm"
                :model="dataForm"
                label-width="8em"
                :rules="dataFormRule"
                class="table-edit-from "
            >

                <el-form-item label="代理商折扣:" prop="user.discount">
                    <span>{{ dataForm.user.discount }}</span>
                </el-form-item>
                <el-form-item label="sku名称:" prop="row.courseName">
                    <span>{{ dataForm.row.name }}</span>
                </el-form-item>
                <el-form-item label="商品单价:" prop="row.agentPrice">
                    <span
                    >{{ priceChange(dataForm.row.agentPrice) }}</span>
                </el-form-item>
                <el-form-item label="开课用户:" prop="userPhone">
                    <el-button
                        v-for="(item, index) in dataForm.userPhone"
                        :key="index"
                        type="primary"
                        plain
                        icon="el-icon-delete"
                        @click="removeUser(index)"
                    >{{ item }}
                    </el-button>
                    <el-button
                        v-show="!phoneDialogFormVisible"
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        @click="() => (phoneDialogFormVisible = true)"
                    >
                    </el-button>
                    <el-input
                        v-if="phoneDialogFormVisible"
                        v-model="dataForm.mobile"
                        style="margin-left: 10px"
                        placeholder="请输入内容"
                    ></el-input>
                    <el-button
                        v-show="phoneDialogFormVisible"
                        type="warning"
                        plain
                        icon="el-icon-close"
                        @click="cancleMobile"
                    >
                    </el-button>
                    <el-button
                        v-show="phoneDialogFormVisible"
                        type="success"
                        plain
                        icon="el-icon-check"
                        @click="okMobile"
                    >
                    </el-button>
                </el-form-item>
                <el-form-item label="商品数量:" prop="userCount">
                    <span>{{ dataForm.userCount }}</span>
                </el-form-item>
                <el-form-item label="支付金额:" prop="money">
                    <span disabled>
                        {{ priceChange(dataForm.money) }}
                    </span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="dialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="
                        myformDataSave(
                            '/order/or/order/agent/open-sku',
                            r => coverDataForm(r)
                        )
                    "
                >保 存</el-button
                >
            </span>
        </el-dialog>
        <el-dialog
            title="提码"
            :modal="false"
            :visible.sync="codeFormVisible"
            :before-close="codeDialogClose"
            custom-class="two-dialog"
        >
            <el-form
                ref="codeForm"
                :model="codeForm"
                label-width="8em"
                class="table-edit-from "
            >

                <el-form-item label="代理商折扣:" prop="user.discount">
                    <span>{{ codeForm.user.discount }}</span>
                </el-form-item>
                <el-form-item label="sku名称:" prop="row.courseName">
                    <span>{{ codeForm.row.name }}</span>
                </el-form-item>
                <el-form-item label="商品单价:" prop="row.agentPrice">
                    <span
                    >{{ priceChange(codeForm.row.agentPrice) }}</span>
                </el-form-item>
                <!--                <el-form-item label="提码数量:" prop="userCount">-->
                <!--                    <span >{{codeForm.userCount}}</span>-->
                <!--                </el-form-item>-->
                <el-form-item label="支付金额:" prop="money">
                    <span disabled>
                        {{ priceChange(codeForm.money) }}
                    </span>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button :loading="submitFlag" @click="codeDialogClose"
                >取 消</el-button
                >
                <el-button
                    :loading="submitFlag"
                    type="primary"
                    @click="myCodeDataSave('/order/or/order/agent/open-sku-code',r => coverDataForm(r))"
                >保 存</el-button
                >
            </span>
        </el-dialog>

        <el-dialog
            title="包含栏目"
            :visible.sync="dialogShow"
            :modal="false"
            custom-class="two-dialog"
            @close="dialogClosed"
        >
            <ul>
                <li v-for="(item, index) in columns" :key="index">
                    {{item.name}}
                </li>
            </ul>
        </el-dialog>
    </div>
</template>

<script>
import {TablePage} from "@/layout/mixin/iVue.js";
import {mapState} from "vuex";
import {get, post} from "@/api/request";
import {treeList2Tree} from "@/utils";
import {getCurrentUserAgent} from "@/api/user";

export default {
    name: "SkuComponent",
    components: {},
    mixins: [TablePage],
    props: {
        packageId: {
            type: String,
            default: "1484059757424672768"
        },
        industryId:{
            type:String
        },
        examId:{
            type:String

        }
    },
    data() {
        return {
            columns:[],
            dialogShow:false,
            skuAttrFlag: false,
            skuAttrList: [],
            props: {
                multiple: false,
                checkStrictly: false,
                emitPath: false,
                label: "name",
                value: "id"
            },

            categoryList:[],
            phoneDialogFormVisible: false,
            codeFormVisible: false,
            examType: null,
            industryData: [],
            examData: [],
            packageData: [],
            productData: [],
            categoryData: [],
            categoryFlag: false,
            productFlag: false,
            industryFlag: false,
            examFlag: false,
            packageFlag: false,
            queryData: {
                base: true,
                name: "",
                industryId: null,
                examId: null,
                packageId: this.packageId,
            },
            categoryProps: {
                //multiple: true,
                checkStrictly: true,
                emitPath: false,
                label: "name",
                value: "id",
            },
            initAddForm: {
                id: null,
                name: null,
                price: null,
                agentPrice: null,
                sort: 100,
                industryId: null,
                examId: null,
                categoryId: null,
                columnIds: [],
                days: null,
                endDate: null,
                examType: "zhiye"
            },
            dataForm: {
                row: {},
                agent: {},
                user: {},
                userCount: 0,
                userPhone: []
            },
            codeForm: {
                row: {},
                agent: {},
                user: {},
                userCount: 0,
            },
            dataFormRule:{},
            initCodeForm: {
                row: {},
                agent: {},
                user: {},
                userCount: 0,
            },
            initDataForm: {
                row: {},
                agent: {},
                user: {},
                mobile:"",
                userCount: 0,
                userPhone: []
            },
        };
    },
    computed: {
        ...mapState({})
    },
    watch: {
        // examType() {
        //     this.queryData.industryId = null;
        // },
        // "queryData.industryId"(industryId) {
        //     this.queryData.examId = null;
        //     if (industryId) {
        //         this.loadExam(industryId);
        //     } else {
        //         this.examData = [];
        //     }
        // },
        // "queryData.examId"(examId) {
        //     this.queryData.packageId = null;
        //     if (examId) {
        //         this.loadPackage(examId);
        //     } else {
        //         this.packageData = [];
        //     }
        // },

    },
    created() {
        // this.loadIndustry();
        this.loadSkuAttr();
        this.loadCategory();
    },
    mounted() {
    },

    methods: {
        showColumns(item){
            get("/exam/product/base/column-details-by-productIds",{
                ids:item.productIds
            }).then(res=>{
                this.columns=res
                this.dialogShow=true
            })
        },
        dialogClosed(){
          this.columns=[]
        },
        search() {
            this.loadTable("/exam/package/sku/page");
        },
        loadSkuAttr() {
            this.skuAttrFlag = true;
            get("/exam/package/sku/attr/list", {size: 1000, enable: true,industryId:this.industryId,examId:this.examId})
                .then(res => {
                    let f=res.filter(r=>{
                        return r.parentId !==null
                    });
                    f.push({name:"单科",id:"danke"})
                    f.push({name:"全科",id:"quanke"})
                    this.skuAttrList = treeList2Tree(f);
                })
                .finally(() => {
                    this.skuAttrFlag = false;
                });
        },
        loadCategory(){
            this.categoryFlag=true
            get("/exam/category/list", {examId:this.examId,size:2000,tree:false})
                .then(res => {
                    this.categoryList = treeList2Tree(res);
                    console.log("categoryList",this.categoryList);
                })
                .finally(() => {
                    this.categoryFlag = false;
                });
        },
        openCourse(row) {
            this.dataForm.row = row;
            this.dataForm.userCount = 0;
            this.dataForm.money = 0;
            this.dataForm.userPhone = [];
            getCurrentUserAgent().then(res => {
                this.dataForm.user = res;
                this.dataForm.addAction = true;
                this.clickSimpleEdit(this.dataForm, "开课");
            });
        },
        openCode(row) {
            this.codeForm.row = row;
            this.codeForm.userCount = 1;
            getCurrentUserAgent().then(res => {
                this.codeForm.user = res;
                this.codeForm.addAction = true;
                this.codeForm.money = (
                    this.codeForm.userCount *
                    this.codeForm.row.agentPrice *
                    this.codeForm.user.discount
                ).toFixed(2);
                this.codeFormVisible = true;
            });
        },
        cancleMobile() {
            this.phoneDialogFormVisible = false;
            this.dataForm.mobile = "";
        },
        removeUser(index) {
            this.dataForm.userPhone.splice(index, 1);
            this.changeCountAndMoney();
        },
        okMobile() {
            if (!this.dataForm.mobile) {
                this.$message({
                    message: "请输入手机号",
                    type: "warning"
                });
                return;
            }
            const reg = /^1[3|4|5|6|7|8|9][0-9]\d{8}$/;
            if (!reg.test(this.dataForm.mobile)) {
                this.$message({
                    message: "手机号格式不对",
                    type: "warning"
                });
                return;
            }
            this.dataForm.userPhone.push(this.dataForm.mobile);
            this.changeCountAndMoney();
            this.dataForm.mobile = "";
            this.phoneDialogFormVisible = false;
        },
        coverDataForm(r) {
            return {
                skuId: r.row.id,
                packageId: this.packageId,
                userPhone: this.dataForm.userPhone
            };
        },
        myformDataSave(
            url,
            cover = r => {
                const copy = {...r};
                if (r.parent && typeof r.parent === "object") {
                    copy.parent = null;
                }
                if (r.children && typeof r.children === "object") {
                    copy.children = null;
                }
                return copy;
            }
        ) {
            return new Promise((r, j) => {
                this.$refs.dataForm.validate(valid => {
                    if (valid) {
                        r();
                    } else {
                        j();
                    }
                });
            })
                .then(() => {
                    this.submitFlag = true;
                    const promise = post(url, cover(this.dataForm));
                    return promise
                        .then(async res => {
                            this.dataForm = this.initDataForm;
                            this.lastVersion = this.thisObjSing(this.dataForm);
                            this.dialogFormVisible = false;
                            this.$message({
                                message: "开课成功",
                                type: "success"
                            });
                            this.search();
                            return res;
                        })
                        .finally(() => {
                            this.submitFlag = false;
                        });
                })
                .catch(e => {
                    console.error(e);
                });
        },
        myCodeDataSave(
            url,
            cover = r => {
                const copy = {...r};
                if (r.parent && typeof r.parent === "object") {
                    copy.parent = null;
                }
                if (r.children && typeof r.children === "object") {
                    copy.children = null;
                }
                return copy;
            }
        ) {
            return new Promise((r, j) => {
                this.$refs.codeForm.validate(valid => {
                    if (valid) {
                        r();
                    } else {
                        j();
                    }
                });
            })
                .then(() => {
                    this.submitFlag = true;
                    const promise = post(url, cover(this.codeForm));
                    return promise
                        .then(async res => {
                            this.codeForm = this.initCodeForm;
                            this.codeFormVisible = false;
                            this.$message({
                                message: "提码成功",
                                type: "success"
                            });
                            this.search();
                            return res;
                        })
                        .finally(() => {
                            this.submitFlag = false;
                        });
                })
                .catch(e => {
                    console.error(e);
                });
        },
        changeCountAndMoney() {
            this.dataForm.userCount = this.dataForm.userPhone.length | 0;
            this.dataForm.money = (
                this.dataForm.userCount *
                this.dataForm.row.agentPrice *
                this.dataForm.user.discount
            ).toFixed(2);
        },
        loadIndustry() {
            this.industryFlag = true;
            get("/exam/industry/list", {size: 1000})
                .then(res => {
                    this.industryData = res;
                })
                .finally(() => {
                    this.industryFlag = false;
                });
        },
        loadExam(industryId, name) {
            this.examFlag = true;
            get("/exam/exam/list", {
                industryId,
                name,
                size: 1000
            })
                .then(res => {
                    this.examData = res;
                })
                .finally(() => {
                    this.examFlag = false;
                });
        },
        loadPackage(examId, name) {
            this.packageFlag = true;
            get("/exam/package/list", {
                examId,
                name,
                size: 1000
            })
                .then(res => {
                    this.packageData = res;
                })
                .finally(() => {
                    this.packageFlag = false;
                });
        },
        priceChange(number) {
            const bs = number / 100;
            return bs.toFixed(2) + "元";
        },
        dialogClose() {
            const w = () => {
                this.dialogFormVisible = false;
                this.dataForm = {...this.initDataForm};
            };
            this.$confirm("数据还未保存，确定关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(w);
        },
        codeDialogClose() {
            const w = () => {
                this.codeFormVisible = false;
                this.codeForm = {...this.initCodeForm};
            };
            this.$confirm("数据还未保存，确定关闭吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(w);
        },
    }
};
</script>

<style lang="scss" scoped>
::v-deep .el-transfer-panel {
    width: 300px;
}
</style>
